﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="BusRoutesManager.aspx.cs" Inherits="GPSTrackingWebsiteManager.Pages.BusRoutesManager" %>

<!DOCTYPE html>

<link href="../../Css/GPSTrackingWebsite.css" rel="stylesheet" />
<link href="../../Css/messi.css" rel="stylesheet" />
<script src="../../Javascript/jquery-1.11.1.min.js"></script>
<script src="../../Javascript/messi.js"></script>
<script src="../../Javascript/Custom.js"></script>
<script src="../../Javascript/WindowMessageManager.js"></script>
<script src="../../Javascript/ObjectsV2.js"></script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
        <script type="text/javascript">

            //Windows Message Manager 
            var objWindowsMessageManager = new WindowsMessageManager();

            var opener = GetRadWindow();
            var BusRoutesManager = new BusRoutesManager();
            var Companies = new Companies();

            function GetRadWindow() {
                var oWindow = null;
                if (window.radWindow)
                    oWindow = window.radWindow;
                else if (window.frameElement.radWindow)
                    oWindow = window.frameElement.radWindow;
                return oWindow.BrowserWindow;
            }

            function initializeObjects() {
                opener.objMapControl.initializeBusRoutesManagerObject();
            }

            function clearObjects() {
                BusRoutesManager.enableDisableBusRouteEventClickMap(opener, false);
                opener.objMapControl.hideDirectionsDisplay(opener.globalBusRoutesManager.directionsDisplay);
                for (i = 0; i < opener.globalBusRoutesManager.polygonoBusRouteMarkers.length; i++) {
                    opener.objMapControl.setVisibleMarker(opener.globalBusRoutesManager.polygonoBusRouteMarkers[i], false);
                }
            }
            
            function restorePage() {
                enableDisableBusRouteEventClickMap();
                opener.objMapControl.showDirectionsDisplay(opener.globalBusRoutesManager.directionsDisplay);
                for (i = 0; i < opener.globalBusRoutesManager.polygonoBusRouteMarkers.length; i++) {
                    opener.objMapControl.setVisibleMarker(opener.globalBusRoutesManager.polygonoBusRouteMarkers[i], true);
                }
            }

            function getCompaniesByAdminUsername() {
                initializeObjects();
                PageMethods.wsGetCompaniesByAdminUsername(getCompaniesByAdminUsernameOk, getCompaniesByAdminUsernameError);
            }

            function getCompaniesByAdminUsernameOk(object) {
                Companies.openXMLCompaniesByAdminUsername(object, opener.globalBusRoutesManager.companiesList);
                Companies.loadCompaniesDataSource(getCompaniesGrid(), opener.globalBusRoutesManager.companiesList, opener.globalBusRoutesManager.companiesDataSource);
                if (opener.globalBusRoutesManager.companiesList.length == 1) {
                    getCompaniesGrid().selectItem(0);
                    if (BusRoutesManager.isValidToGetBusRoutes(opener, opener.globalBusRoutesManager.companiesList[0].companyID, getBusRoutesGrid())) {
                        getBusRoutesByCompanyID();
                    }
                }
            }

            function getCompaniesByAdminUsernameError(error) {
                responseEnd(getrpvBusRoutesManagerUpdateControl());
                objWindowsMessageManager.show_Error(error.get_message(), titles.busRoutesTitle);
            }

            function CompaniesGrid_OnRowClick(sender, args) {
                if (BusRoutesManager.isValidToGetBusRoutes(opener, args.getDataKeyValue("CompanyID"), getBusRoutesGrid())) {
                    requestStart(getrpvBusRoutesManagerUpdateControl());
                    BusRoutesManager.clearBusRoutes(opener);
                    setBtnBusRouteToSave();
                    getBusRoutesByCompanyID();
                }
            }

            function getBusRoutesByCompanyID() {
                PageMethods.wsGetBusRoutesByCompanyID(opener.globalBusRoutesManager.companyID, getBusRoutesByCompanyIDOk, getBusRoutesByCompanyIDError);
            }

            function getBusRoutesByCompanyIDOk(object) {
                BusRoutesManager.openXMLBusRoutesByCompanyID(object, opener.globalBusRoutesManager.busRoutesList);
                loadBusRoutesDataSourceWait();
                responseEnd(getrpvBusRoutesManagerUpdateControl());
            }

            function getBusRoutesByCompanyIDError(error) {
                responseEnd(getrpvBusRoutesManagerUpdateControl());
                objWindowsMessageManager.show_Error(error.get_message(), titles.busRoutesTitle);
            }

            function loadBusRoutesDataSourceWait() {
                BusRoutesManager.loadBusRoutesDataSource(getBusRoutesGrid(), opener.globalBusRoutesManager.busRoutesList, opener.globalBusRoutesManager.busRoutesDataSource);
                responseEnd(getrpvBusRoutesManagerUpdateControl());
            }

            function BusStopsGrid_OnRowClick(sender, args) {
                if (BusRoutesManager.busStopGridOnRowClick(opener, args)) {
                    BusStopDeleteCompletely();
                }
            }

            function isValidToInsertBusRoute() {
                requestStart(getrpvBusRoutesManagerUpdateControl());
                var objects = { busRouteName: getRtbBusRouteName().value, latList: [], lngList: [], isBtnBusRouteToSave: isBtnBusRouteToSave() }
                if (BusRoutesManager.isValidToInsertBusRoute(opener, objects)) {
                    if (isBtnBusRouteToSave()) {
                        InsertBusRoutesDetails(objects);
                    }
                    else {
                        UpdateBusRoutesDetails(objects);
                    }
                }
                else {
                    responseEnd(getrpvBusRoutesManagerUpdateControl());
                }
            }

            function getStepsFromRoute() {
                var contador = 0;
                var text = "";
                if (opener.globalBusRoutesManager.busRoutes.length > 0) {
                    for (l = 0; l < opener.globalBusRoutesManager.busRoutes[0].legs.length; l++) {
                        for (s = 0; s < opener.globalBusRoutesManager.busRoutes[0].legs[l].steps.length; s++) {
                            for (p = 0; p < opener.globalBusRoutesManager.busRoutes[0].legs[l].steps[s].path.length; p++) {
                                contador = contador + 1;
                                text = contador.toString();
                                opener.objMapControl.addMarker(null, opener.globalBusRoutesManager.busRoutes[0].legs[l].steps[s].path[p], text);
                                //alert(opener.globalBusRoutesManager.busRoutes[0].legs[l].steps[s].path[p]);
                            }
                        }
                    }
                }
                //var lat = opener.globalBusRoutesManager.busRoutes[0].legs[0].steps[0].path[0].lat();
                //objWindowsMessageManager.show_Info(lat);
                responseEnd(getrpvBusRoutesManagerUpdateControl());
            }

            function InsertBusRoutesDetails(objects) {
                //getStepsFromRoute();
                PageMethods.wsBusRoutesDetailsInsert(opener.globalBusRoutesManager.companyID, objects.busRouteName, objects.latList, objects.lngList, InsertBusRoutesDetailsOk, InsertBusRoutesDetailsError);
            }

            function InsertBusRoutesDetailsOk(busRouteID) {
                if (busRouteID == -1) {
                    objWindowsMessageManager.show_Warning("La ruta indicada ya existe registrada para esta compañía.", titles.busRoutesTitle);
                }
                else {
                    opener.globalBusRoutesManager.isSeletedItemBusRoute = true;
                    BusRoutesManager.busRouteInsertSuccessful(opener, busRouteID, getBusRoutesGrid(), getRtbBusRouteName().value);
                    getRtbBusRouteName().value = "";
                    setBtnBusRouteToUpdate();
                    opener.globalBusRoutesManager.busRouteID = busRouteID;
                    objWindowsMessageManager.show_Info("La ruta se insertó correctamente.", titles.busRoutesTitle);
                }
                responseEnd(getrpvBusRoutesManagerUpdateControl());
            }

            function InsertBusRoutesDetailsError(error){
                responseEnd(getrpvBusRoutesManagerUpdateControl());
                objWindowsMessageManager.show_Error(error.get_message(), titles.busRoutesTitle);
            }

            function UpdateBusRoutesDetails(objects) {
                PageMethods.wsBusRoutesDetailsUpdate(opener.globalBusRoutesManager.busRouteID, objects.latList, objects.lngList, UpdateBusRoutesDetailsOk, UpdateBusRoutesDetailsError);
            }

            function UpdateBusRoutesDetailsOk() {
                responseEnd(getrpvBusRoutesManagerUpdateControl());
                objWindowsMessageManager.show_Info("La ruta se actualizó correctamente.", titles.busRoutesTitle);
            }

            function UpdateBusRoutesDetailsError(error) {
                responseEnd(getrpvBusRoutesManagerUpdateControl());
                objWindowsMessageManager.show_Error(error.get_message(), titles.busRoutesTitle);
            }

            function BusRoutesGrid_RowSelecting(sender, args) {
                if (!opener.globalBusRoutesManager.isSeletedItemBusRoute) {
                    opener.globalBusRoutesManager.isSeletedItemBusRoute = true;
                    BusRoutesManager.busRoutesGridRowSelecting(opener, args.getDataKeyValue("BusRouteID"));
                    setBtnBusRouteToUpdate();
                    GetAllBusRouteDetailsByBusRouteID();
                }
            }

            function GetAllBusRouteDetailsByBusRouteID(){
                requestStart(getrpvBusRoutesManagerUpdateControl());
                PageMethods.wsGetAllBusRouteDetailsByBusRouteID(opener.globalBusRoutesManager.busRouteID, GetAllBusRouteDetailsByBusRouteIDOk, GetAllBusRouteDetailsByBusRouteIDError);
            }

            function GetAllBusRouteDetailsByBusRouteIDOk(object) {
                BusRoutesManager.clearBusRoutes(opener);
                opener.globalBusRoutesManager.isValidClickPoint = true;
                opener.globalBusRoutesManager.isSeletedItemBusRoute = true;
                BusRoutesManager.openXMLBusRouteDetailsByBusRouteID(object, opener.globalBusRoutesManager);

                opener.globalBusRoutesManager.temporalyIndex = 0;
                opener.globalBusRoutesManager.temporalyInterval = setInterval(function () { loadBusRouteDisplay(opener); }, opener.globalBusRoutesManager.timeToCalculateRoute);   
            }

            function loadBusRouteDisplay(opener) {
                if (opener.globalBusRoutesManager.temporalyIndex < opener.globalBusRoutesManager.temporalyList.length) {
                    opener.objMapControl.addBusRouteMarkersClickDB(opener.globalBusRoutesManager.temporalyList[opener.globalBusRoutesManager.temporalyIndex++]);
                }
                else {
                    clearInterval(opener.globalBusRoutesManager.temporalyInterval);
                    responseEnd(getrpvBusRoutesManagerUpdateControl());
                }
            }

            function GetAllBusRouteDetailsByBusRouteIDError(error) {
                objWindowsMessageManager.show_Error(error.get_message(), titles.busRoutesTitle);
                responseEnd(getrpvBusRoutesManagerUpdateControl());
            }

            function BusRoutesGrid_OnRowClick(sender, args) {
                opener.globalBusRoutesManager.isSeletedItemBusRoute = false;
                if (BusRoutesManager.busRoutesGridOnRowClick(opener, args)) {
                    BusRouteDeleteCompletely();
                }
            }

            function BusRouteDeleteCompletely() {
                requestStart(getrpvBusRoutesManagerUpdateControl());
                getBusRoutesGrid().clearSelectedItems();

                if (opener.globalBusRoutesManager.busRouteID != -1) {
                    PageMethods.wsBusRouteDelete(opener.globalBusRoutesManager.companyID, opener.globalBusRoutesManager.busRouteID, BusRouteDeleteCompletelyOk, BusRouteDeleteCompletelyError);
                }
                else {
                    responseEnd(getrpvBusRoutesManagerUpdateControl());
                    objWindowsMessageManager.show_Warning("Debe seleccionar una ruta de bus para eliminarla.", titles.busRoutesTitle);
                }
            }

            function BusRouteDeleteCompletelyOk(object) {
                if (object = "true") {
                    
                    clearBusRoutes();
                    getBusRoutesGrid().clearSelectedItems();
                    opener.globalBusRoutesManager.busRoutesList.splice(BusRoutesManager.getIndexBusRouteID(opener.globalBusRoutesManager.busRoutesList, opener.globalBusRoutesManager.busRouteID), 1);
                    clearDataSource(opener.globalBusRoutesManager.busRoutesDataSource, getBusRoutesGrid(), false);
                    BusRoutesManager.loadBusRoutesDataSource(getBusRoutesGrid(), opener.globalBusRoutesManager.busRoutesList, opener.globalBusRoutesManager.busRoutesDataSource);
                    responseEnd(getrpvBusRoutesManagerUpdateControl());
                    objWindowsMessageManager.show_Info("Se eliminó correctamente la parada de bus.", titles.busRoutesTitle);
                }
                else {
                    responseEnd(getrpvBusRoutesManagerUpdateControl());
                    objWindowsMessageManager.show_Error("No se eliminó correctamente la ruta de bus.", titles.busRoutesTitle);
                }
            }

            function BusRouteDeleteCompletelyError(error) {

                if (error.get_message().indexOf("FK_BusStopByBusRoutes_BusRoutes" != -1)) {
                    objWindowsMessageManager.show_Warning("No se puede eliminar la ruta porque tiene asociada paradas definidas.", titles.busRoutesTitle);
                }
                else {
                    objWindowsMessageManager.show_Error(error.get_message(), titles.busRoutesTitle);
                }
                responseEnd(getrpvBusRoutesManagerUpdateControl());
            }

            function BusRoutesGrid_RowDeselecting(sender, args) {
                var index = BusRoutesManager.getIndexBusRouteID(opener.globalBusRoutesManager.busRoutesList, args.getDataKeyValue("BusRouteID"));
                if (index != -1) {
                    opener.globalBusRoutesManager.busRoutesList[index].checked = false;
                }
            }
            
            function getBusRoutesGrid() {
                try {
                    return $find("<%= rgBusRoutesGrid.ClientID %>").get_masterTableView();
                }
                catch (ex) {
                    setTimeout(getBusRoutesGrid, 100);
                }
            }

            function getCompaniesGrid() {
                try {
                    return $find("<%= rgCompaniesGrid.ClientID %>").get_masterTableView();
                }
                catch (ex) {
                    setTimeout(getCompaniesGrid, 100);
                }
            }

            function getrpvBusRoutesManagerUpdateControl() {
                return "<%=  rpvBusRoutesManager.ClientID %>";
            }

            function enableDisableBusRouteEventClickMap() {
                BusRoutesManager.enableDisableBusRouteEventClickMap(opener, getCkbBusRoutes().checked);
            }

            function clearBusRoutes() {
                BusRoutesManager.clearBusRoutes(opener);
                getBusRoutesGrid().clearSelectedItems();
                setBtnBusRouteToSave();
            }

            function getRtbBusRouteName() {
                return $get('<%= rtbBusRouteName.ClientID %>');
            }

            function getBtnBusRoute() {
                return $get('btnBusRouteSave');
            }

            function setBtnBusRouteToSave() {
                getBtnBusRoute().value = "Guardar Ruta";
            }

            function setBtnBusRouteToUpdate() {
                getBtnBusRoute().value = "Actualizar Ruta";
            }

            function isBtnBusRouteToSave() {
                return (getBtnBusRoute().value == "Guardar Ruta");
            }

            function getCkbBusRoutes() {
                return $get('<%= ckbBusRoutes.ClientID %>');
            }

            function requestStart(object) {
                try {
                    $find("<%= RadAjaxLoadingPanel1.ClientID%>").show(object);
                }
                catch (e) {
                    null;
                }
            }

            function responseEnd(object) {
                try {
                    $find("<%= RadAjaxLoadingPanel1.ClientID%>").hide(object);
                }
                catch (e) {
                    null;
                }
            }

        </script>
    </telerik:RadScriptBlock>
    <style type="text/css">
        .auto-style1
        {
            width: 153px;
        }
    </style>
</head>
<body onload="getCompaniesByAdminUsername()">

    <form id="form1" runat="server">
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true"></telerik:RadScriptManager>
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <AjaxSettings>
					<telerik:AjaxSetting AjaxControlID="AjaxControlID1">
						<UpdatedControls>
							<telerik:AjaxUpdatedControl ControlID="Loading" LoadingPanelID="RadAjaxLoadingPanel1" />
						</UpdatedControls>
					</telerik:AjaxSetting>
				</AjaxSettings>
        </telerik:RadAjaxManager>

        <telerik:RadTabStrip ID="rtsBusRoutesManager" runat="server" SelectedIndex="0" MultiPageID="rmpBusRoutesManager" >
        </telerik:RadTabStrip>
        <telerik:RadMultiPage ID="rmpBusRoutesManager" runat="server"  SelectedIndex="0">
            <telerik:RadPageView ID="rpvBusRoutesManager" runat="server">

                <table style="width: 100%; text-align: left">
		             <tr>
                        <td colspan="2">
                            <fieldset>
								<legend>Nueva Ruta</legend>
								<table class="auto-style2">
									<tr>
										<td class="auto-style1">
											<asp:CheckBox ID="ckbBusRoutes" runat="server" onclick="javascript:enableDisableBusRouteEventClickMap()" Text="Habilitar Marcadores" Width="200px"/>
                                            <input id="btnClearBusRoutes" type="button" value="Limpiar Marcadores" onclick="clearBusRoutes();" />
										</td>
									<td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
										<td>Nombre de la Ruta:</td>
										<td>
											<telerik:RadTextBox ID="rtbBusRouteName" runat="server" AutoPostBack="false">
											</telerik:RadTextBox>
										</td>
										<td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
										<td>
											<input id="btnBusRouteSave" type="button" value="Guardar Ruta" onclick="isValidToInsertBusRoute();" />
										</td>
									</tr>
								</table>
                            </fieldset>
                        </td>
                    </tr>
                    <tr>
                        <td>
                  
				            <fieldset>
					            <legend>Compañias Registradas</legend>
					            <telerik:RadGrid ID="rgCompaniesGrid" runat="server" AllowMultiRowSelection="False" AutoGenerateColumns="False" CellSpacing="0" GridLines="None" Height="100px" OnNeedDataSource="rgCompaniesGrid_NeedDataSource"  Width="300px">
						            <ClientSettings>
							            <Selecting AllowRowSelect="True" />
							            <ClientEvents OnRowClick="CompaniesGrid_OnRowClick" />
							            <Scrolling AllowScroll="True" UseStaticHeaders="true" />
						            </ClientSettings>
						            <MasterTableView EditMode="PopUp" EditFormSettings-PopUpSettings-Modal="true" EditFormSettings-CaptionFormatString="Modo Edición" ClientDataKeyNames="CompanyID" NoMasterRecordsText="No hay compañias registradas">
							            <CommandItemSettings ExportToPdfText="Export to PDF" />
							            <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column" Visible="True">
							            </RowIndicatorColumn>
							            <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column" Visible="True">
							            </ExpandCollapseColumn>
							            <Columns>
								            <telerik:GridBoundColumn DataField="CompanyID" FilterControlAltText="Filter Description column" HeaderText="ID" UniqueName="CompanyID" Display="false">
								            </telerik:GridBoundColumn>
								            <telerik:GridBoundColumn DataField="Name" FilterControlAltText="Filter Description column" HeaderText="Nombre">
								            </telerik:GridBoundColumn>
							            </Columns>
							            <EditFormSettings>
								            <EditColumn FilterControlAltText="Filter EditCommandColumn column">
								            </EditColumn>
							            </EditFormSettings>
						            </MasterTableView>
						            <FilterMenu EnableImageSprites="true">
						            </FilterMenu>
					            </telerik:RadGrid>
				            </fieldset>
			            </td>
			            <td>
                  
				            <fieldset>
					            <legend>Grupos de Rutas Registrados</legend>
					            <telerik:RadGrid ID="rgBusRoutesGrid" runat="server" AllowMultiRowSelection="False" AutoGenerateColumns="False" CellSpacing="0" GridLines="None" Height="100px" OnNeedDataSource="rgBusRoutesGrid_NeedDataSource"  Width="300px">
						            <ClientSettings>
							            <Selecting AllowRowSelect="True" />
							            <ClientEvents OnRowClick="BusRoutesGrid_OnRowClick" OnRowDeselecting="BusRoutesGrid_RowDeselecting" OnRowSelecting="BusRoutesGrid_RowSelecting" />
							            <Scrolling AllowScroll="True" UseStaticHeaders="true" />
						            </ClientSettings>
						            <MasterTableView EditMode="PopUp" EditFormSettings-PopUpSettings-Modal="true" EditFormSettings-CaptionFormatString="Modo Edición" ClientDataKeyNames="BusRouteID" NoMasterRecordsText="No hay Grupos de Rutas registrados">
							            <CommandItemSettings ExportToPdfText="Export to PDF" />
							            <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column" Visible="True">
							            </RowIndicatorColumn>
							            <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column" Visible="True">
							            </ExpandCollapseColumn>
							            <Columns>
                                            <telerik:GridImageColumn ImageUrl="..\..\Template\Icons\16px\Delete.gif" UniqueName="DeleteColumn" ItemStyle-Width="40px" HeaderStyle-Width="40px">
								            </telerik:GridImageColumn>
								            <telerik:GridBoundColumn DataField="BusRouteID" FilterControlAltText="Filter Description column" HeaderText="ID" UniqueName="BusRouteID" Visible="false">
								            </telerik:GridBoundColumn>
								            <telerik:GridBoundColumn DataField="Name" FilterControlAltText="Filter Description column" HeaderText="Nombre" Visible="true">
								            </telerik:GridBoundColumn>
							            </Columns>
							            <EditFormSettings>
								            <EditColumn FilterControlAltText="Filter EditCommandColumn column">
								            </EditColumn>
							            </EditFormSettings>
						            </MasterTableView>
						            <FilterMenu EnableImageSprites="true">
						            </FilterMenu>
					            </telerik:RadGrid>
				            </fieldset>
			            </td>
		            </tr>
	            </table>
            </telerik:RadPageView>
        </telerik:RadMultiPage>
          
        <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Default"></telerik:RadAjaxLoadingPanel>
    </form>
</body>
</html>
